package com.gdca.sdk.ca;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;

import java.util.List;
import java.util.logging.Level;

import com.gdca.sdk.ca.listener.GdcaLoginListener;
import com.gdca.sdk.ca.listener.GdcaResultListener;
import com.gdca.sdk.ca.listener.ReqListener;
import com.gdca.sdk.ca.listener.RequestCallBack;
import com.gdca.sdk.ca.model.ResponseContent;
import com.gdca.sdk.ca.model.ResultModel;
import com.gdca.sdk.ca.utils.DeviceInfo;
import com.gdca.sdk.ca.utils.NetworkUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.store.PersistentCookieStore;
import com.lzy.okgo.model.HttpHeaders;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * Created by Dell on 2017/3/14.
 */

public class SdkManager {
    public static String TAG = "cloud sign";
    public static final int TYPE_SIGN = 1;
    public static final int TYPE_BIND = 2;
    public static final int TYPE_LOGIN = 3;

    public static String app_id = null;//teJefN5XjEXZm1iq
    public static String app_secret = null;//wuVSvQ9P_IpqXv8cpO3c_8LkrVpbrAis134WeogarrP9wogJHAQcOSUypLsX8VnE

    private volatile static SdkManager instance;
    private boolean isCheck = false;
    private static NetworkUtil netWork;

    public SdkManager() {

    }

    public static SdkManager getInstance() {
        if (instance == null) {
            synchronized (SdkManager.class) {
                if (instance == null) {
                    instance = new SdkManager();
                }
            }
        }
        return instance;
    }

    public static void init(Application application, String code, String secret) {
        app_id = code;
        app_secret = secret;
//        netWork = new NetworkUtil();

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.put("mediumType", "1");
            headers.put("medium", DeviceInfo.getDeviceId(application));
            headers.put("channelCode", "1");
            headers.put("sysVersion", DeviceInfo.getAndroidRelease());
            headers.put("phoneModel", DeviceInfo.getManufacturer() + " " + DeviceInfo.getModel());

            OkGo.init(application);
            OkGo.getInstance()
                    .debug("11111")
                    .setConnectTimeout(Config.DEFULT_TIME_OUT)  //全局的连接超时时间
                    .setReadTimeOut(Config.DEFULT_TIME_OUT)     //全局的读取超时时间
                    .setWriteTimeOut(Config.DEFULT_TIME_OUT)    //全局的写入超时时间
                    .setCacheMode(CacheMode.NO_CACHE)
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                    .setRetryCount(0)
                    .setCookieStore(new PersistentCookieStore())
                    .addCommonHeaders(headers);
            if (BuildConfig.DEBUG) {
                OkGo.delete("sdk");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public void requestSign(long id) {
//        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
//        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
//        if (pinfo != null) {
//            for (int i = 0; i < pinfo.size(); i++) {
//                String pn = pinfo.get(i).packageName;
//                if ("com.gdca.cloudsign".equals(pn)) {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("cs://gdca/cloudsign?packName=" + context.getPackageName() + "&id=" + id + "&type=1"));
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY);
//                    context.startActivity(intent);
//                    return;
//                }
//            }
//            Toast.makeText(context, "not install", Toast.LENGTH_SHORT).show();
//        } else {
//            Toast.makeText(context, "not install", Toast.LENGTH_SHORT).show();
//        }
//    }

    public void requestBind(final Context mContext, String userBusId, String accountName, String notifyUrl, final GdcaResultListener listener) {
        if (!isCheck) {
            listener.onResultError(mContext.getString(R.string.error_check));
            return;
        }
        try {
            NetworkUtil.requestBind(mContext, userBusId, accountName, notifyUrl, new RequestCallBack() {
                @Override
                public void onError(int code, Call call, Exception e) {
                    if (listener != null) {
                        listener.onResultError(e.getMessage());
                    }
                }

                @Override
                public void onTimeout(boolean needRetry, String msg) {
                    super.onTimeout(needRetry, msg);
                    if (listener != null) {
                        listener.onResultError(mContext.getString(R.string.time_out));
                    }
                }

                @Override
                public void onFail(int code, String msg) {
                    if (listener != null) {
                        listener.onResultError(msg);
                    }
                }

                @Override
                public void onSuccess(ResponseContent content) {
                    if (content.isSuccess()) {
                        try {
                            JSONObject object = new JSONObject(content.getContent());
                            String claimTaskId = object.getString("claimTaskId");
                            baseRequest(mContext, "&claimTaskId=" + claimTaskId, TYPE_BIND, listener);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        listener.onResultError(content.getMessage());
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void baseRequest(Context mContext, String data, int type, GdcaResultListener listener) {
        PackageManager packageManager = mContext.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if ("com.gdca.cloudsign".equals(pn)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("cs://gdca/cloudsign?packName=" + mContext.getPackageName() + "&type=" + type + data));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                    mContext.startActivity(intent);
                    listener.onResultSuccess(1);
                    return;
                }
            }
            Toast.makeText(mContext, "not install", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "not install", Toast.LENGTH_SHORT).show();
        }
    }

    public void requestLogin(final Context mContext, String notifyUrl, final GdcaResultListener listener) {
        if (!isCheck) {
            listener.onResultError(mContext.getString(R.string.error_check));
            return;
        }
        try {
            NetworkUtil.requestLogin(mContext, notifyUrl, new RequestCallBack() {
                @Override
                public void onError(int code, Call call, Exception e) {
                    if (listener != null) {
                        listener.onResultError(e.getMessage());
                    }
                }

                @Override
                public void onFail(int code, String msg) {
                    if (listener != null) {
                        listener.onResultError(msg);
                    }
                }

                @Override
                public void onTimeout(boolean needRetry, String msg) {
                    super.onTimeout(needRetry, msg);
                    if (listener != null) {
                        listener.onResultError(mContext.getString(R.string.time_out));
                    }
                }

                @Override
                public void onSuccess(ResponseContent content) {
                    if (content.isSuccess()) {
                        try {
                            JSONObject object = new JSONObject(content.getContent());
                            String claimTaskId = object.getString("claimTaskId");
                            baseRequest(mContext, "&claimTaskId=" + claimTaskId, TYPE_LOGIN, listener);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        listener.onResultError(content.getMessage());
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void handleIntent(Context mContext, Intent intent, final ReqListener listener) {
        //获取指定参数值
        final int type = intent.getIntExtra("type", 1);
        final int result = intent.getIntExtra("result", -1);
        if (type == TYPE_SIGN) {
            final String id = intent.getStringExtra("id");
            final String token = intent.getStringExtra("token");
            if (result == NetworkUtil.RESULT_SUCCESS) {
                netWork.requestSignResult(mContext, id, token, new NetworkUtil.ResultCallBack() {
                    @Override
                    public void onSuccess(Object model) {
                        if (listener != null) {
                            listener.onResp(result, type, (ResultModel) model);
                        }
                    }

                    @Override
                    public void onFail(String message, int code) {

                    }
                });
            } else {
                if (listener != null) {
                    listener.onResp(result, type, null);
                }
            }
        } else if (type == TYPE_BIND) {
            getBindResult(mContext, intent, listener);
        } else if (type == TYPE_LOGIN) {
            getLoginResult(mContext, intent, listener);
        }
    }

    private void getLoginResult(Context mContext, Intent intent, ReqListener listener) {
        long signTaskId = intent.getLongExtra("id", 0);
        if (signTaskId == 0) {
            if (listener != null) {
//                listener.onResp(result, type, null);
            }
            return;
        }
        try {
            NetworkUtil.getLoginResult(mContext, signTaskId, new RequestCallBack() {
                @Override
                public void onError(int code, Call call, Exception e) {

                }

                @Override
                public void onFail(int code, String msg) {

                }

                @Override
                public void onSuccess(ResponseContent content) {
                    if (content.isSuccess()) {

                    } else {

                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            if (listener != null) {
//                listener.onResp(result, type, null);
            }
        }
    }

    private void getBindResult(Context mContext, Intent intent, final ReqListener listener) {
        long signTaskId = intent.getLongExtra("id", 0);
        if (signTaskId == 0) {
            if (listener != null) {
//                listener.onResp(result, type, null);
            }
            return;
        }
        try {
            NetworkUtil.getBindResult(mContext, signTaskId, new RequestCallBack() {
                @Override
                public void onError(int code, Call call, Exception e) {

                }

                @Override
                public void onFail(int code, String msg) {

                }

                @Override
                public void onSuccess(ResponseContent content) {
                    if (content.isSuccess()) {

                    } else {

                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            if (listener != null) {
//                listener.onResp(result, type, null);
            }
        }
    }

    public void checkLogin(final Context context, final GdcaLoginListener callBack) {
        try {
            NetworkUtil.checkSdk(context, new RequestCallBack() {
                @Override
                public void onError(int code, Call call, Exception e) {
                    if (callBack != null) {
                        callBack.onLoginError(code, e.getMessage());
                    }
                }

                @Override
                public void onTimeout(boolean needRetry, String msg) {
                    super.onTimeout(needRetry, msg);
                    if (callBack != null) {
                        callBack.onLoginError(Config.NETWORK_TIMEOUT_ERROR, context.getString(R.string.time_out));
                    }
                }

                @Override
                public void onFail(int code, String msg) {
                    if (callBack != null) {
                        callBack.onLoginError(Config.OTHER_ERROR, msg);
                    }
                }

                @Override
                public void onSuccess(ResponseContent content) {
                    if (content.isSuccess()) {
                        isCheck = true;
                        if (callBack != null) {
                            callBack.onLoginSuccess(0);
                        }
                    } else {
                        callBack.onLoginError(content.getCode(), content.getMessage());
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
